trigger Attachment_InUse on Attachment (before delete) 
{
	List<ID> batchIdList = new list<ID>();
	Map<ID,String> batchNamesMap = new Map<ID, String>();
	Map<ID,String> batchStatusMap = new Map<ID, String>();
	
	String bName = '';
	Boolean deleteAttachFlag = true;
	Boolean flag = false;
	List<ID> parentIdList = new List<ID>();
    String BatchNames = '';
	
    if(Trigger.isDelete)
    {
		Set<Id> attachmentIdSet = Trigger.oldMap.keyset();
		
    	for(Attachment attachmentObj: Trigger.oldMap.values())
    	{
    		parentIdList.add(attachmentObj.parentId);
    	}
    	
        for(CallidusDataSource__c[] cdsList : [select In_Use_Attachments__c from CallidusDataSource__c where id in :parentIdList])
        {
        	for(CallidusDataSource__c cds: cdsList)
        	{
        		for(Id idVal: attachmentIdSet)
        		{
        			if(cds.In_Use_Attachments__c != null && cds.In_Use_Attachments__c.indexOf(idVal) != -1)
                		Trigger.oldMap.get(idVal).addError('You can\'t delete this Attachment.');
        		}
        	}
        }
        
        for(Batch__c[] b : [Select Id, Name, Status__c from Batch__c b where b.Template__c in :parentIdList])
        {
            for(Batch__c batch: b)
            {
                batchIdList.add(batch.Id);

                if(batch.Status__c == 'Distributed')
                    batchStatusMap.put(batch.Id, batch.Status__c);

                if(batch.Status__c == 'Completed')
                    batchNamesMap.put(batch.Id, batch.Name);
                        
                if(batchIdList.size() == b.size())
                {
                    flag = false;
                    for(Sales_Contract__c[] sc : [select Id, BatchID__c from Sales_Contract__c where BatchID__c in :batchIdList and AttachmentID__c in :Trigger.oldMap.keyset()])
                    {
                        if(sc.size() > 0)
                        {
                            flag = true;
                            for(Sales_Contract__c sContract: sc)
                            {
                                
                                if(batchStatusMap.get(sContract.BatchID__c) == 'Distributed')
                                    deleteAttachFlag = false;
                            
                                bName = batchNamesMap.get(sContract.BatchID__c);
                                if(bName != null)
                                    BatchNames += bName+'\n';

                            }
                        }
                            
                    }
                            
                    if(flag == false)
                    {
                        Attachment[] att = [select Name, Body from Attachment where Id in :Trigger.oldMap.keySet()];
                        String body = att[0].Body.toString();
                        Integer indexOfBody = body.indexOf('<body', 0);
                        if(indexOfBody == -1)
                            indexOfBody = body.indexOf('<Body', 0);
            
                        if(indexOfBody == -1)
                            indexOfBody = body.indexOf('<BODY', 0);
                        
                        String extractedBody = '';
                        if(indexOfBody != -1)
                        {
                            extractedBody = body.substring(indexOfBody);
                        
                            Integer indexOfLFB = extractedBody.indexOf('{', 0);
                            Integer indexOfRFB = extractedBody.indexOf('}', 0);
                            
                            if(indexOfLFB == -1 && indexOfRFB == -1)
                                deleteAttachFlag = false;
                        }

                        if(att[0].Name.indexOf('.doc') != -1)
                            deleteAttachFlag = false;
                    }                                

                    batchIdList.clear();
                }//end of if(batchIdList.size() == ....
                       
            }
        }
        if(deleteAttachFlag == false)
            Trigger.old[0].addError('You can\'t delete this Attachment.');
        else if(BatchNames != '')
            Trigger.old[0].addError('The Attachment can not be deleted as the below batches are using it.\n'+BatchNames);
        else
        {
        	Set<ID> errorIdVals = new Set<ID>();
        	for(sales_contract__c[] scList : [select id, attachmentid__c from sales_contract__c where attachmentid__c in :Trigger.oldMap.keySet()])
        	{
	        	for(sales_contract__c sc: scList)
	        	{
	        		if(Trigger.oldMap.get(sc.attachmentid__c) != null && !errorIdVals.contains(sc.attachmentid__c))
	        		{
						Trigger.oldMap.get(sc.attachmentid__c).addError('You can\'t delete this Attachment as it has been used to generate Plan Documents.');
						errorIdVals.add(sc.attachmentid__c);
	        		}				
	        	}
        	}
        }
    }        
}